import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/api/user.dart';
import 'package:flutter_enjoy_plus/utils/EvenBus.dart';
import 'package:flutter_enjoy_plus/utils/PromptAction.dart';
import 'package:flutter_enjoy_plus/utils/TokenManager.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  // 手机号控制器
  final TextEditingController _phoneController = TextEditingController();
  // 验证码控制器
  final TextEditingController _codeController = TextEditingController();
  // 定时器ID
  Timer? _timer;
  // 定时秒数
  int _duration = 60;

  // 发送验证码
  _sendCode() async {
    // 获取验证码
    if (_duration == 60) {
      // 验证输入内容
      if (_phoneController.text.isEmpty) {
        return Promptaction.showError('手机号不能为空');
      }
      // 手机号码格式的正则
      RegExp reg = RegExp(r'^1[3-9]\d{9}$');
      if (!reg.hasMatch(_phoneController.text)) {
        return Promptaction.showError('手机号码格式不正确');
      }
      setState(() {
        _duration--;
      });
      // 验证通过，发送验证码请求
      final res = await getCodeAPI({
        'mobile': _phoneController.text,
      });
      Future.delayed(const Duration(seconds: 3), () {
        _codeController.text = res['code'];
      });
      // 开始倒计时
      _beginCount();
    }
  }

  // 开启倒计时
  void _beginCount() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_duration == 1) {
        _duration = 60;
        timer.cancel();
      } else {
        _duration--;
      }
      setState(() {});
    });
  }

  // 获取倒计时显示文本
  Widget getTimerShow() {
    if (_duration < 60) {
      return Text('还剩$_duration秒');
    }
    return const Text('发送验证码');
  }

  // 登录
  void _login() async {
    // 获取验证码
    // _phoneController.text;
    // _codeController.text;
    if (_phoneController.text.isEmpty || _codeController.text.isEmpty) {
      Promptaction.showError("手机号和验证码不能为空");
      return;
    }
    RegExp pReg = RegExp(r'^1[3-9]\d{9}$'); // 手机号正则
    RegExp cReg = RegExp(r'^\d{6}$'); // 验证码正则
    if (!pReg.hasMatch(_phoneController.text) ||
        !cReg.hasMatch(_codeController.text)) {
      Promptaction.showError("手机号和验证码格式不正确");
      return;
    }
    // 发送接口
    var res = await loginAPI(
        {"mobile": _phoneController.text, "code": _codeController.text});
    tokenManager.setToken(res["token"], refreshToken: res["refreshToken"]);
    _timer?.cancel();
    if (mounted) {
      Navigator.pop(context);
      // 发布事件 -- 重新获取用户信息
      eventBus.fire(LoginEvent());
    }
  }

  @override
  void initState() {
    super.initState();
    // 设置手机号
    _phoneController.text = '18812345678';
  }

  @override
  void dispose() {
    super.dispose();
    _timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('登录'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: Container(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const Row(
              children: [
                Text(
                  '登录',
                  style: TextStyle(
                    fontSize: 25,
                    fontWeight: FontWeight.bold,
                  ),
                )
              ],
            ),
            const SizedBox(height: 10),
            const Row(
              children: [
                Text(
                  '加入享+, 让生活更轻松',
                  style: TextStyle(fontSize: 15),
                )
              ],
            ),
            const SizedBox(height: 30),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Expanded(
                  child: TextField(
                    controller: _phoneController,
                    decoration: const InputDecoration(
                      labelText: '手机号',
                      hintText: '请输入手机号',
                    ),
                  ),
                ),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    shadowColor: Colors.transparent,
                    foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    _sendCode();
                  },
                  child: getTimerShow(),
                ),
              ],
            ),
            const SizedBox(height: 8),
            TextField(
              controller: _codeController,
              decoration: const InputDecoration(
                labelText: '验证码',
                hintText: '请输入6位验证码',
              ),
            ),
            const SizedBox(height: 8),
            const Row(
              children: [
                Text(
                  '未注册手机号经验证后将自动登录',
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                ),
              ],
            ),
            const SizedBox(height: 50),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      // TODO 目前在未登录状态也可以点击，可以进行优化
                      _login();
                    },
                    child: const Text(
                      '登录',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                      ),
                    ),
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}
